package com.ykdl.member.kid.fittool;
import java.util.Calendar;
import java.util.Date;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ykdl.member.kid.R;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.adapters.BodyAdapter;
import com.ykdl.member.kid.beans.BodyListBean;
import com.ykdl.member.kid.beans.BodyTypeBean;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.DatePickerWheel;
import com.ykdl.member.views.DatePickerWheel.OnDateChangedListener;

/**
 * 升高体重头围
 * @author Pengfei
 *
 */
public class HeightWeightHeadActivity extends BaseActivity implements 
		OnClickListener, OnRefreshListener, OnItemLongClickListener{
	
	public static String TAG = HeightWeightHeadActivity.class.getSimpleName();
	
	private RefreshListView mListView;
	private ProgressDialog mProgressDialog;
	private BodyAdapter mAdapter;
	private int cursor = 0;
	private int count = 50;
	private int type = 0;
	
	private View mLayerAddPage, mLayerWheel;
	private EditText mEditHeight;
	private TextView mTxtDate, mTxtSmallTitle;
	private DatePickerWheel mDateWheel;
	private Calendar mInitCalendar;
	private BodyListTag mBodyListTag;
	private int mDateType;
	private Button mBtnCross,mBtnLeftArrows,mBtnRightArrows,mBtnRight;
	
	private ImageView mImgArrow;
	private View mLayerMenu;
	private TextView mTxtAll, mTxtHeight, mTxtWeight, mTxtHead;
	private TextView mTxtTitle;
	
	private View mLayerHeight, mLayerWeight, mLayerHead;
	private int viewType;
	private final int TYPE_HEIGHT = 1;
	private final int TYPE_WEIGHT = 2;
	private final int TYPE_HEAD = 3;
	private TextView mTxtLaberValue, mTxtUnit;
	private int mPosition;
	private long record_time;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_height_weight_head);
		initView();
		
		mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading_data), true, true);
		mBodyListTag = new BodyListTag();
		Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
	}
	
	private void initView(){
		mTxtTitle = (TextView) findViewById(R.id.txtTitle);
		findViewById(R.id.btnBack).setOnClickListener(this);
		mImgArrow = (ImageView) findViewById(R.id.imgArrow);
		mImgArrow.setOnClickListener(this);
		mLayerMenu = findViewById(R.id.layerMenu);
		mLayerMenu.setOnClickListener(this);
		mTxtAll = (TextView) findViewById(R.id.txtAll);
		mTxtAll.setOnClickListener(this);
		mTxtHeight = (TextView) findViewById(R.id.txtHeight);
		mTxtHeight.setOnClickListener(this);
		mTxtWeight = (TextView) findViewById(R.id.txtWeight);
		mTxtWeight.setOnClickListener(this);
		mTxtHead = (TextView) findViewById(R.id.txtHead);
		mTxtHead.setOnClickListener(this);
		
		
		mListView = (RefreshListView) findViewById(R.id.listView);
		mLayerHeight = findViewById(R.id.layerHeight);
		mLayerHeight.setOnClickListener(this);
		mLayerWeight = findViewById(R.id.layerWeight);
		mLayerWeight.setOnClickListener(this);
		mLayerHead = findViewById(R.id.layerHead);
		mLayerHead.setOnClickListener(this);
		
		mAdapter = new BodyAdapter(this);
		mListView.setAdapter(mAdapter);
		mListView.setonRefreshListener(this);
		mListView.setMoreClick(null);
		
		mListView.setOnItemLongClickListener(this);
		
		mLayerAddPage = findViewById(R.id.layerAddPage);
		mTxtLaberValue = (TextView) findViewById(R.id.txtLaberValue);
		mEditHeight = (EditText) findViewById(R.id.editHeight);
		mEditHeight.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO
				if (TextUtils.isEmpty(s.toString().trim())) {
					return;
				}
				float value = Float.valueOf(s.toString());
				if (viewType == TYPE_HEIGHT) {
					if (value < 20 || value > 180) {
						mEditHeight.setTextColor(getResources().getColor(R.color.pure_red));
					} else {
						mEditHeight.setTextColor(getResources().getColor(R.color.gray));
					}
				} else if (viewType == TYPE_WEIGHT) {
					if (value < 3 || value > 100) {
						mEditHeight.setTextColor(getResources().getColor(R.color.pure_red));
					} else {
						mEditHeight.setTextColor(getResources().getColor(R.color.gray));
					}
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		mTxtUnit = (TextView) findViewById(R.id.txtUnit);
		mTxtDate = (TextView) findViewById(R.id.txtDate);
		
		mLayerWheel = findViewById(R.id.layerWheel);
		mDateWheel = (DatePickerWheel) findViewById(R.id.datePickerWheel);
		mBtnCross = (Button) findViewById(R.id.btnCross);
		mBtnCross.setOnClickListener(this);
		mBtnLeftArrows = (Button) findViewById(R.id.btnLeftArrows);
		mBtnLeftArrows.setOnClickListener(this);
		mBtnRightArrows = (Button) findViewById(R.id.btnRightArrows);
		mBtnRightArrows.setOnClickListener(this);
		mBtnRight = (Button) findViewById(R.id.btnRight);
		mBtnRight.setOnClickListener(this);
		mTxtSmallTitle = (TextView) findViewById(R.id.txtSmallTitle);
		
		Calendar caMinDate = Calendar.getInstance();
		caMinDate.set(2010, 0, 1);
		mDateWheel.setMinDate(caMinDate.getTimeInMillis());
		mDateWheel.setMaxDate(new Date().getTime());
		mInitCalendar = Calendar.getInstance();
		mDateWheel.init(mInitCalendar.get(Calendar.YEAR),
				mInitCalendar.get(Calendar.MONTH),
				mInitCalendar.get(Calendar.DAY_OF_MONTH), new DateChangedListener());
	}
	
	private class DateChangedListener implements OnDateChangedListener{

		@Override
		public void onDateChanged(DatePickerWheel view, int year,
				int monthOfYear, int dayOfMonth) {
			mTxtDate.setText(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
			Calendar calendar = Calendar.getInstance();
			calendar.set(year, monthOfYear, dayOfMonth);
			calendar.getTimeInMillis();
			record_time =  calendar.getTimeInMillis()/1000;
		}
		
	}

	@Override
	public void onClick(View v) {
		float value;
		switch (v.getId()) {
		case R.id.imgArrow:
			if (mLayerMenu.getVisibility() == View.VISIBLE) {
				mImgArrow.setImageResource(R.drawable.title_downarrow);
				mLayerMenu.setVisibility(View.GONE);
				activeAddView();
			} else {
				mImgArrow.setImageResource(R.drawable.title_uparrow);
				mLayerMenu.setVisibility(View.VISIBLE);
				antiActiveAddView();
			}
			break;
		case R.id.txtAll:
			if (mLayerMenu.getVisibility() == View.VISIBLE && type != 0) {
				mImgArrow.setImageResource(R.drawable.title_downarrow);
				mLayerMenu.setVisibility(View.GONE);
				activeAddView();
				mTxtTitle.setText("身高体重头围");
				cursor = 0;
				type = 0;
				mProgressDialog.show();
				mAdapter.cleanData();
				Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
			}
			break;
		case R.id.txtHeight:
			if (mLayerMenu.getVisibility() == View.VISIBLE && type != BodyTypeBean.TYPE_HEIGHT) {
				mImgArrow.setImageResource(R.drawable.title_downarrow);
				mLayerMenu.setVisibility(View.GONE);
				activeAddView();
				mTxtTitle.setText("身高");
				cursor = 0;
				type = BodyTypeBean.TYPE_HEIGHT;
				mProgressDialog.show();
				mAdapter.cleanData();
				Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
			}
			break;
		case R.id.txtWeight:
			if (mLayerMenu.getVisibility() == View.VISIBLE && type != BodyTypeBean.TYPE_WEIGHT) {
				mImgArrow.setImageResource(R.drawable.title_downarrow);
				mLayerMenu.setVisibility(View.GONE);
				activeAddView();
				mTxtTitle.setText("体重");
				cursor = 0;
				type = BodyTypeBean.TYPE_WEIGHT;
				mProgressDialog.show();
				mAdapter.cleanData();
				Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
			}
			break;
		case R.id.txtHead:
			if (mLayerMenu.getVisibility() == View.VISIBLE && type != BodyTypeBean.TYPE_HEAD) {
				mImgArrow.setImageResource(R.drawable.title_downarrow);
				mLayerMenu.setVisibility(View.GONE);
				activeAddView();
				mTxtTitle.setText("头围");
				cursor = 0;
				type = BodyTypeBean.TYPE_HEAD;
				mProgressDialog.show();
				mAdapter.cleanData();
				Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
			}
			break;
		case R.id.btnBack:
			finish();
			break;
		case R.id.layerHeight:
			// TODO 跳转到添加身高记录界面
			viewType = TYPE_HEIGHT;
			mEditHeight.setText(null);
			mTxtDate.setText(null);
			mListView.setEnabled(false);
			antiActiveAddView();
			showKeyboard();
			mDateType = BodyTypeBean.TYPE_HEIGHT;
			mTxtSmallTitle.setText(R.string.fittool_height);
			mTxtLaberValue.setText(R.string.baby_height);
			mTxtUnit.setText("cm");
			break;
		case R.id.layerWeight:
			// TODO 跳转到体重记录添加界面
			viewType = TYPE_WEIGHT;
			mEditHeight.setText(null);
			mTxtDate.setText(null);
			mListView.setEnabled(false);
			antiActiveAddView();
			showKeyboard();
			mDateType = BodyTypeBean.TYPE_WEIGHT;
			mTxtSmallTitle.setText(R.string.fittool_weight);
			mTxtLaberValue.setText(R.string.baby_weight);
			mTxtUnit.setText("kg");
			break;
		case R.id.layerHead:
			// TODO 跳转到头围记录添加界面
			viewType = TYPE_HEAD;
			mEditHeight.setText(null);
			mTxtDate.setText(null);
			mListView.setEnabled(false);
			antiActiveAddView();
			showKeyboard();
			mDateType = BodyTypeBean.TYPE_HEAD;
			mTxtSmallTitle.setText(R.string.fittool_head);
			mTxtLaberValue.setText(R.string.baby_head);
			mTxtUnit.setText("cm");
			break;
		case R.id.iask_root_loadmore:
			Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
			break;
		case R.id.btnCross:
			hideKeyBoard();
			activeAddView();
			mLayerAddPage.setVisibility(View.GONE);
			mListView.setEnabled(true);
			break;
		case R.id.btnLeftArrows:
			mLayerWheel.setVisibility(View.GONE);
			mBtnCross.setVisibility(View.VISIBLE);
			mBtnLeftArrows.setVisibility(View.GONE);
			mBtnRightArrows.setVisibility(View.VISIBLE);
			mBtnRight.setVisibility(View.GONE);
			if (viewType == TYPE_HEIGHT) {
				mTxtSmallTitle.setText(R.string.fittool_height);
			} else if (viewType == TYPE_WEIGHT) {
				mTxtSmallTitle.setText(R.string.fittool_weight);
			} else if (viewType == TYPE_HEAD) {
				mTxtSmallTitle.setText(R.string.fittool_head);
			}
			showKeyboard();
			
			break;
		case R.id.btnRightArrows:
			if (TextUtils.isEmpty(mEditHeight.getText().toString())) {
				Toast.makeText(this, "数据不能为空", 1).show();
				return;
			}
			hideKeyBoard();
			value = Float.valueOf(mEditHeight.getText().toString());
			if (viewType == TYPE_HEIGHT && (value < 20 || value > 180)) {
				Toast.makeText(this, "身高值的范围是20~180cm", 1).show();
				return;
			} else if (viewType == TYPE_WEIGHT && (value < 3 || value > 100)) {
				Toast.makeText(this, "身高值的范围是3~100kg", 1).show();
				return;
			}
			mLayerWheel.setVisibility(View.VISIBLE);
			mBtnCross.setVisibility(View.GONE);
			mBtnLeftArrows.setVisibility(View.VISIBLE);
			mBtnRightArrows.setVisibility(View.GONE);
			mBtnRight.setVisibility(View.VISIBLE);
			mTxtSmallTitle.setText("日期");
		    
			break;
		case R.id.btnRight:
			//保存数据
			value = Float.valueOf(mEditHeight.getText().toString());
			mProgressDialog.show();
			
			Network.getInstance().addBodyTypeBean(mDateType, value, record_time,new AddDataTag());
			activeAddView();
			break;
		default:
			break;
		}
	}
	
	private void activeAddView() {
		mLayerHeight.setClickable(true);
		mLayerWeight.setClickable(true);
		mLayerHead.setClickable(true);
	}
	
	private void antiActiveAddView() {
		mLayerHeight.setClickable(false);
		mLayerWeight.setClickable(false);
		mLayerHead.setClickable(false);
	}
	
	private void retryAddView(){
		mLayerAddPage.setVisibility(View.GONE);
		mLayerWheel.setVisibility(View.GONE);
		mBtnCross.setVisibility(View.VISIBLE);
		mBtnLeftArrows.setVisibility(View.GONE);
		mBtnRightArrows.setVisibility(View.VISIBLE);
		mBtnRight.setVisibility(View.GONE);
	}
	
	private void showKeyboard(){
		mLayerAddPage.setVisibility(View.VISIBLE);
		mEditHeight.setFocusable(true);
		mEditHeight.setFocusableInTouchMode(true);
		mEditHeight.requestFocus();
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(mEditHeight, 0);
	}
	
	private void hideKeyBoard(){
		//隐藏键盘
		mEditHeight.setFocusable(false);
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEditHeight.getWindowToken(), 0);
	}
	
	private class BodyListTag implements ITag<BodyListBean>{
		
		@Override
		public void refreshUI(BodyListBean t, DataState ds) {
			// TODO Auto-generated method stub
			mProgressDialog.dismiss();
			if(t instanceof BodyListBean && t != null){
				BodyListBean body = (BodyListBean) t;
				if (t.getBaby_profile() != null) 
					mAdapter.setBaby(t.getBaby_profile());
				if (cursor == 0) mAdapter.cleanData();
				mAdapter.addBeans(body.getList());
				mAdapter.notifyDataSetChanged();
				if (body.getNext_cursor() == body.getTotal_number()) {
					mListView.setMoreButtoIsGon(true);
				} else {
					cursor = body.getNext_cursor();
				}
			} else {
				Toast.makeText(HeightWeightHeadActivity.this, R.string.loaded_data_fail, Toast.LENGTH_SHORT).show();
			}
			onRefreshComplate();
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			Toast.makeText(HeightWeightHeadActivity.this, R.string.loaded_data_fail, Toast.LENGTH_SHORT).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
	}
	
	private class AddDataTag implements ITag<StatuResult>{

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			mProgressDialog.dismiss();
			retryAddView();
			if (t != null && t.getResult() == 0 && TextUtils.isEmpty(t.getDesc())) {
				mProgressDialog = ProgressDialog.show(HeightWeightHeadActivity.this, null, getString(R.string.loading_data), true, true);
				Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
			} else {
				Toast.makeText(HeightWeightHeadActivity.this, "添加数据失败", 1).show();
			}
			mListView.setEnabled(true);
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			mProgressDialog.dismiss();
			Toast.makeText(HeightWeightHeadActivity.this, "添加数据失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		
	}
	
	private class DelDataTag implements ITag<StatuResult>{

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null && t.getResult() == 0) {
				mAdapter.getBeans().remove(mDelBean);
				mAdapter.notifyDataSetChanged();
			} else {
				Toast.makeText(HeightWeightHeadActivity.this, "删除数据失败", 1).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			mProgressDialog.dismiss();
			Toast.makeText(HeightWeightHeadActivity.this, "删除数据失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		
	}


	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		cursor = 0;
		type = 0;
		Network.getInstance().requestBodyRecordList(cursor, count, type, mBodyListTag);
	}
	
	public void onRefreshComplate(){
		mListView.onRefreshComplete();
	}
	
	private void delData(int id){
		
	}
	
	private static final int DIALOG_DELETE_DATA = 1;
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DELETE_DATA:
			Dialog dialog = new AlertDialog.Builder(this).setMessage("是否删除?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					if (mDelBean != null) 
						Network.getInstance().deleteBodyTypeBean(mDelBean.getId(), new DelDataTag());
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).create();
			return dialog;

		default:
			return super.onCreateDialog(id);
		}
	}

	private BodyTypeBean mDelBean;
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		mDelBean = (BodyTypeBean) mAdapter.getItem(position - 1);
		showDialog(DIALOG_DELETE_DATA);
		return false;
	}
}
